#---------------------------------------------------------------------------------------#
# R code to accompany "The geography of Green votes in Melbourne: a tutorial with ggmap" 
# Author: kyle peyton (kyle.peyton@yale.edu)
#
# created 25 June 2014 
# last update 22 July 2014
#---------------------------------------------------------------------------------------#

require(ggmap) ## load the ggmap package 
require(grid)
qmap("melbourne", zoom=12)

qmap("melbourne", zoom=12, source ="stamen", maptype="toner")

## layering maps with data 
GreenVotes = read.csv("GreenVotes.csv")

### examine top 10 polling places for GreenVotes in 2013 
indx <- order(GreenVotes$VoteShare,decreasing=TRUE)[1:10]
GreenVotes[indx,c("VoteShare","DivisionNm","state","Latitude","Longitude")]


## simplest example
VoteMap <- qmap("Melbourne,Australia", zoom = 12, legend = "topright")

### ugly base 
VoteMap +
    geom_point(aes(x = Longitude, y = Latitude, size = VoteShare),
               data = GreenVotes, shape= 21, fill = "darkgreen")

### some bells and whistles
VoteMap +
    geom_point(aes(x = Longitude, y = Latitude, size = VoteShare, alpha = VoteShare, fill = VoteShare),
               data = GreenVotes, shape= 21) +
    scale_size_area(breaks=seq(10,50,5), max_size=15)  + 
    scale_fill_gradient(high= "darkgreen", low ="white", name= "GRN 1st Prefs", breaks=seq(10,80,10), labels= paste(seq(10,80,10),"%",sep="")) +
    guides(alpha="none", size="none") +
    theme(legend.text = element_text(color= 'black', size = 12),
          legend.key = element_rect(fill = 'white', size = 0.5, linetype='solid'),
          legend.key.size = unit(1.5, 'lines'),
          legend.background = element_rect(fill=alpha('white',0.75)),
          text = element_text(family = "serif", size = 14))

## assign weights to polling places proportion to the number of votes made & make contour plot
GreenVotes2 <- with(GreenVotes, GreenVotes[rep(1:nrow(GreenVotes), VoteShare),])
VoteMap +
    stat_density2d(
        aes(x = Longitude, y = Latitude, fill = ..level.., alpha = ..level..),
        size = 2,  data = GreenVotes2,
        geom = "polygon") + scale_fill_gradient(high = "darkgreen",low="white", name="GRN 1st Prefs. Density") + 
    guides(alpha="none") +
    theme(legend.text = element_text(color= 'black', size = 12),
          legend.key = element_rect(fill = 'white', size = 0.5, linetype='solid'),
          legend.key.size = unit(1.5, 'lines'),
          legend.background = element_rect(fill=alpha('white',0.75)),
          text = element_text(family = "serif", size = 14))
